<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/15
 * Time: 23:46
 */

namespace App\Library\form_builder\src\components;
use App\Library\form_builder\src\traits\Validate;
//Input父类
class BaseForm
{
    use Validate;
    // 标题
    protected $title='';
    //name字段
    protected $field='';
    //
    protected $value='';
    //属性
    protected $props='';
    //值
    protected $values=[];
    //验证测试
    protected $valids=[];

    //组件依赖文件
    protected $depends=[

    ];
    //组件加载JS
    protected $Js=[

    ];
    //是否基于layui
    protected $FrameName='layui'; //默认layui前端框架
    public function __construct($title,$field,$value=null){
        $this->title=$title;
        $this->field=$field;
        empty($value)?$this->value=$value:null;
    }
    //设置属性
    /**
     *  data-id=1  disable=disabld placeholder=''
     *  $props=[disable=>disabld]
     */
    public function set_props($props){

        $join='';
        if(is_array($props)){
            foreach($props as $item=>$value){
                if(is_numeric($item)){
                    throw new \Exception("键不能为数值");
                }else {
                    $join.="{$item}='{$value}'".' ';
                }
            }
        }else if(is_string($props)){
            if($this->check_prop($props)){
                $join=$props;
            }
        }
        if(!empty($join)){
            if(empty($this->props)){
                $this->props=$join;
            }else{
                $this->props.=' '.$join;
            }
        }

        return $this;
    }

    /**
     * @param $valids
     * @throws \Exception
     *  [
        'title' => 'required|unique:posts|max:255',
        'author.name' => 'required',
        'author.description' => 'required',
        ]
     */
    public function set_validate($valids){
        if(is_array($valids)) {
            $this->valids = $valids;
        }else{
            throw new \Exception("验证参数只能为数组");
        }
    }
    //验证是否是合格的标签属性
    public  function check_prop($prop){
        if(empty($prop)){
            throw new \Exception("属性不能为空");
        }else{
            //规则是 data-id="1";
            $array=explode('=',$prop);
            if(!isset($array[1])){
                throw new \Exception("不符合属性规则");
            }
            return true;
        }
    }
    /**
     * 获取组件的字段名
     *
     * @return String
     */
    public function getfield()
    {
        return $this->field;
    }
    //获取组件全部参数
    public function get_parameter(){
        $data= array(
            'parameter'=>[
                'title'=>$this->title,
                'field'=>$this->field,
                'values'=>$this->values,
                'props'=>$this->props,
                'valids'=>$this->valids
            ]
        );
        return $data;
    }
}